package cn.edu.zjicm.wordsnet_d.adapter.common;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;

import android.widget.BaseAdapter;

/**
 * Adapter 类基本的ArrayList实现，不同步
 * @author MR
 *
 * @param <T>
 */
public abstract class SortedListAdapter<T extends Comparable<T>> extends BaseAdapter{
	
	private ArrayList<T> mList;
	
	public SortedListAdapter() {
		mList = new ArrayList<T>();
	}
	
	public SortedListAdapter(ArrayList<T> list){
		mList = list;
	}

	@Override
	public int getCount() {
		return mList.size();
	}

	@Override
	public T getItem(int position) {
		if(position < 0 || position >= mList.size()){
			return null;
		}
		return mList.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}
	
	public void addAll(Collection<T> c){
		mList.addAll(c);
		Collections.sort(mList);
		notifyDataSetChanged();
	}

	public void add(T item){
		mList.add(item);
		notifyDataSetChanged();
	}
	
	public void sort(){
		Collections.sort(mList);
		notifyDataSetChanged();
	}
	
	public void clear(){
		mList.clear();
		notifyDataSetChanged();
	}
	
	public boolean remove(T item){
		boolean success = mList.remove(item);
		if(success){
			Collections.sort(mList);
		}
		notifyDataSetChanged();
		return success;
	}
	
	public void replace(int position, T item){
		mList.set(position, item);
		notifyDataSetChanged();
	}
	
}
